const state = {
  operators: [
    // 示例数据
    { id: 1, name: 'ScriptOperator', type: '基础组件', processingMethod: 'Script 脚本', description: '示例脚本算子', content: 'print("Hello, World!")' },
    { id: 2, name: 'RegXOperator', type: '通用算子', processingMethod: 'RegX 正则表达式', description: '示例正则表达式算子', content: '^\\d{3}-\\d{2}-\\d{4}$' },
    { id: 3, name: 'JsonOperator', type: '自定义算子', processingMethod: 'JSON', description: '示例JSON算子', content: '{"key": "value"}' },
    { id: 4, name: 'KVOperator', type: '自定义算子', processingMethod: 'K-V 键值对', description: '示例键值对算子', content: 'key=value' }
  ]
};

const mutations = {
  SET_OPERATORS(state, operators) {
    state.operators = operators;
  },
  ADD_OPERATOR(state, operator) {
    state.operators.push(operator);
  },
  UPDATE_OPERATOR(state, updatedOperator) {
    const index = state.operators.findIndex(operator => operator.id === updatedOperator.id);
    if (index !== -1) {
      state.operators.splice(index, 1, updatedOperator);
    }
  },
  DELETE_OPERATOR(state, operatorId) {
    state.operators = state.operators.filter(operator => operator.id !== operatorId);
  }
};

const actions = {
  fetchOperators({ commit }) {
    // 模拟异步请求
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 500);
    }).then(() => {
      // 在实际应用中，这里应该是从后端获取数据
      commit('SET_OPERATORS', state.operators);
    });
  },
  addOperator({ commit }, operator) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 500);
    }).then(() => {
      commit('ADD_OPERATOR', operator);
    });
  },
  updateOperator({ commit }, updatedOperator) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 500);
    }).then(() => {
      commit('UPDATE_OPERATOR', updatedOperator);
    });
  },
  deleteOperator({ commit }, operatorId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 500);
    }).then(() => {
      commit('DELETE_OPERATOR', operatorId);
    });
  }
};

const getters = {
  operators: state => state.operators,
  operatorCategories: state => {
    const categories = {};
    state.operators.forEach(operator => {
      if (!categories[operator.type]) {
        categories[operator.type] = [];
      }
      categories[operator.type].push(operator);
    });
    return Object.keys(categories).map(categoryName => ({
      name: categoryName,
      operators: categories[categoryName]
    }));
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
